# -*- coding: utf-8 -*-
#from datetime import timedelta
import time
import math
import datetime

from google.appengine.ext.webapp import template

register = template.create_template_register()

def zh_timesince(d, now=None):
    if not d:
        return ''
        
    chunks = (
        (60 * 60 * 24 * 365, '年'),
        (60 * 60 * 24 * 30, '月'),
        (60 * 60 * 24 * 7, '周'),
        (60 * 60 * 24, '天'),
        (60 * 60, '小时'),
        (60, '分钟'),
        (1, '秒')
    )
    # Convert datetime.date to datetime.datetime for comparison
    if d.__class__ is not datetime.datetime:
        d = datetime.datetime(d.year, d.month, d.day)
    if now:
        t = now.timetuple()
    else:
        t = time.localtime()
    if d.tzinfo:
        tz = LocalTimezone(d)
    else:
        tz = None
    now = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], tzinfo=tz)

    # ignore microsecond part of 'd' since we removed it from 'now'
    delta = now - (d - datetime.timedelta(0, 0, d.microsecond))
    if delta.days > 3:
        return timezone(d, 8)
#    from irhelper import *
#    set_trace()
    since = delta.days * 24 * 60 * 60 + delta.seconds
    for i, (seconds, name) in enumerate(chunks):
        count = since / seconds
        if count != 0:
            break
    if count == 0:
        return '%d毫秒' % math.floor((now - d).microseconds / 1000)
    s = '%d%s' % (count, name)
    if i + 2 < len(chunks):
        # Now get the second item
        seconds2, name2 = chunks[i + 1]
        count2 = (since - (seconds * count)) / seconds2
        if count2 != 0:
            s += ', %d%s' % (count2, name2)
    return s
        
register.filter(zh_timesince)

def absfilter(number):
	return abs(number)
	
register.filter(absfilter)

def datefilter(date):
	"""Formats the given date in RFC 3339 format for feeds."""
	if not date: return ''
	date = date + datetime.timedelta(seconds = -time.timezone)
	if time.daylight:
		date += datetime.timedelta(seconds = time.altzone)
	return date.strftime('%m/%d/%Y %H:%M:%S')
	
register.filter(datefilter) 
	
def timezone(value, offset):
    return value + datetime.timedelta(hours=offset)
	
register.filter(timezone)

@register.filter
def truncate(value, arg):
    """
    Truncates a string after a given number of chars  
    Argument: Number of chars to truncate after
    """
    try:
        length = int(arg)
    except ValueError: # invalid literal for int()
        return value # Fail silently.
    if not isinstance(value, basestring):
        value = str(value)
    if (len(value) > length):
        return value[:length] + "..."
    else:
        return value

register.filter(truncate)
